#!/usr/bin/env python3
# _*_ coding:utf-8 _*_

import re
from django.utils.deprecation import MiddlewareMixin
from django.shortcuts import HttpResponse, redirect, render
from django.conf import settings


class RbacMiddleware(MiddlewareMixin):
    def process_request(self, request):

        current_url = request.path_info
        for valid_url in settings.VALID_URL_LIST:
            if re.match(valid_url, current_url):
                return None

        permission_dict = request.session.get(settings.PERMISSION_SESSION_KEY)
        if not permission_dict:
            return redirect('rbac:login')

        url_record = [
            {'title': '首页', 'url': '/'}
        ]
        for url in settings.NO_PERMISSION_LIST:
            if re.match(url, request.path_info):
                request.current_selected_permission = 0
                if url == '/rbac/changepasswd/':
                    url_record.append({'title': '修改密码', 'url': '/rbac/changepasswd/'})
                request.breadcrumb = url_record
                return None

        flag = False

        for k, item in permission_dict.items():
            reg = "^%s$" % item['url']
            if re.match(reg, current_url):
                flag = True
                request.current_selected_permission = item['pid'] or item['id']
                if not item['pid']:
                    url_record.extend([
                        {'title': item['title'], 'url': item['url'], 'class': 'active'},
                    ], )
                else:
                    url_record.extend([
                        {'title': item['pid_title'], 'url': item['pid_url']},
                        {'title': item['title'], 'url': item['url'], 'class': 'active'},
                    ])
                request.breadcrumb = url_record
        if not flag:
            return render(request, '403.html')
